﻿using ComponentFactory.Krypton.Toolkit;
using Microsoft.TeamFoundation.Client;
using Nini.Config;
using System;
using System.Net;
using System.Windows.Forms;

namespace TfsHelper.WinFrontEnd
{
    public partial class frmLogin : KryptonForm
    {
        #region " Fields "

        private IConfigSource config = new XmlConfigSource(Application.StartupPath + "\\Config.xml");
        private TeamFoundationServer tfs = null;
        private string uri = "";

        #endregion

        #region " Constructor "

        public frmLogin(TeamFoundationServer tfsSrv, string uri)
        {
            InitializeComponent();
            lblTfsUrl.Text = uri;
            tfs = tfsSrv;
            this.uri = uri;
        }

        #endregion

        #region " Handlers "

        private void frmLogin_Load(object sender, EventArgs e)
        {

        }

        private void btnLogin_Click(object sender, EventArgs e)
        {
            if (tfs == null)
                tfs = new TeamFoundationServer(uri, new NetworkCredential(txtAccount.Text, txtPassword.Text));
            else
            {
                NetworkCredential cred = tfs.Credentials as NetworkCredential;
                cred.UserName = txtAccount.Text;
                cred.Password = txtPassword.Text;
            }
            try
            {
                tfs.EnsureAuthenticated();
                Close();
            }
            catch (Exception exc)
            {
                KryptonMessageBox.Show("There was an error. Please try again.\n(" + exc.Message + ")", "Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void lblUrl_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            frmTfsUrl url = new frmTfsUrl();
            url.StartPosition = FormStartPosition.CenterParent;
            if(url.ShowDialog()== System.Windows.Forms.DialogResult.OK)
                lblTfsUrl.Text = uri;
        }

        #endregion
    }
}
